//
//  ArrayList.c
//  LC3Compiler
//
//  Created by Anthony Sierra on 6/1/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include "ArrayList.h"

void initializeArrayList(ArrayList * list)
{   
    assert(list != NULL);
    list->items = (Symbol **)malloc(10 * sizeof(Symbol));
    for (int i = 0; i < 10; i++)
    {
        list->items[i] = (Symbol *)malloc(sizeof(Symbol));  
    }
    list->listSize = 0;
    list->arraySize = 10;

}
void destroyArrayList(ArrayList * list)
{   
    assert(list != NULL);
    
    free(list->items);

}
int getSize(const ArrayList * list)
{   
    assert(list != NULL);
    
    return list->listSize;

}
Symbol* getItem(const ArrayList * list, int index)
{  
    assert(list != NULL);
    assert(index >= 0 && index < list->listSize);
    return list->items[index];

}
void setItem(ArrayList * list, int index, Symbol *symbol)
{   
    assert(list != NULL);
    assert(index >= 0 && index < list->listSize);
    Symbol *thing = (Symbol*)malloc(sizeof(Symbol));
    thing->name = symbol->name;
    thing->line_number = symbol->line_number;
    list->items[index] = thing;
    free(thing);

}
void addItemToEndOfArrayList(ArrayList * list, Symbol *value)
{   
    int i;
    Symbol **tmp;
    
    assert(list != NULL);
    
    if (list->listSize == list->arraySize)
    {
        // No more room in the array, so get a bigger array.
        tmp = (Symbol **)malloc(list->arraySize * 2 * sizeof(Symbol));
        assert(tmp != NULL);
        for (i = 0; i < list->arraySize; ++i)
            tmp[i] = list->items[i];
        free(list->items);
        list->items = tmp;
        list->arraySize *= 2;
    }
    // Store the new item in the array.
    list->items[list->listSize] = value;
    ++list->listSize;

}
void addItemBeforeItem(ArrayList * list, int index, Symbol *value)
{
    int i;
    Symbol **tmp;
    
    assert(list != NULL);
    assert(index >= 0 && index < list->listSize);
    
    if (list->listSize == list->arraySize)
    {
        // No more room in the array, so get a bigger array.
        tmp = (Symbol **)malloc(list->arraySize * 2 * sizeof(Symbol));
        assert(tmp != NULL);
        for (i = 0; i < list->arraySize; ++i)
            tmp[i] = list->items[i];
        free(list->items);
        list->items = tmp;
        list->arraySize *= 2;
    }
    
    // Move all items following the new item one element to the right.
    for (i = list->listSize; i > index; --i)
        list->items[i] = list->items[i-1];
    
    // Store the new item in the array.
    list->items[index] = value;
    ++list->listSize;
}
